package com.jhg.drgclinicalpathway.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.util.PoitlIOUtils;
import com.jhg.drgclinicalpathway.dao.*;
import com.jhg.drgclinicalpathway.domain.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.Id;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class FormWordService {


    @Autowired
    PatientDao patientDao;


    @Autowired
    Dis2PathwayDao dis2PathwayDao;

    /**
     * 处理路径ID
     * @param id
     * @return
     */
    public PatientInfo 处理路径ID(String id){
        PatientInfo info = patientDao.selectById(id);

        String 路径ID=info.get路径ID();
        if(StringUtils.isEmpty(路径ID)&&!StringUtils.isEmpty(info.getDiscode())){
            QueryWrapper<Dis2Pathway> queryWrapper = new QueryWrapper<Dis2Pathway>();
            queryWrapper.eq("疾病编码",info.getDiscode());
            List<Dis2Pathway> dis2Pathways = dis2PathwayDao.selectList(queryWrapper);
            if(dis2Pathways.size()>0){
                info.set路径ID(String.valueOf(dis2Pathways.get(0).getWayid()));
//                return String.valueOf(dis2Pathways.get(0).getWayid());
            }
        }

        return info;
    }

   public static Map<String, KeyVal> 内外科正则=new HashMap<String,KeyVal>(){
        {
            put("1",new KeyVal(){
                {
                    setK1("(?i).[r-z].+");
                    setK2("内科版");
                }
            });
            put("2",new KeyVal(){
                {
                    setK1("(?i).[k-q].+");
                    setK2("操作版");
                }
            });
            put("3",new KeyVal(){
                {
                    setK1("(?i).[a-j].+");
                    setK2("手术版");
                }
            });
        }
    };

    public static String 获取路径版本(String drgCode){

        if(StringUtils.isEmpty(drgCode)) return "";

        for (Map.Entry<String, KeyVal> entry : 内外科正则.entrySet()) {
            if(Pattern.matches(entry.getValue().getK1().toString(), drgCode)){
                return entry.getKey();
            }
        }
        return  "";
    }

    public void gender(String id, HttpServletResponse rep) throws Exception {
        PatientInfo info = 处理路径ID(id);

        if(StringUtils.isEmpty(info.get路径ID())){
            return;
        }
        TplForm tpl = getTpl(info.get路径ID(),获取路径版本(info.getDrgcode()));

        ClassPathResource resource = new ClassPathResource("/tpl/"+tpl.getRsize()+"列临床路径模板.docx");
        // 2.判断模板是否存在
        if (!resource.exists()) {
            throw new Exception(resource.getFilename()+" 没找到！");
        }

        // 3.用数据填充模板
        InputStream wordTmpl = resource.getInputStream();

        // 获取单位名称
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(false);
        //生成参数
        Map<String, Object> params=generParams(info,tpl);
        XWPFTemplate template = XWPFTemplate.compile(wordTmpl, builder.build()).render(params);
        // 4.关闭模板文档
        wordTmpl.close();
        // 5.以网络流形式输出
        rep.setContentType("application/octet-stream");
        rep.setCharacterEncoding("UTF-8");
        String fileName =new String(info.getPatname() .getBytes("UTF-8"), "iso-8859-1") ;
        rep.setHeader("Content-disposition",
                "attachment;filename=" + fileName+ ".docx");
        // HttpServletResponse response
        rep.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        OutputStream out = rep.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        template.close();

    }

    @Autowired
    PathTplDao pathTplDao;


    /**
     * 获取模板
     * @param 路径ID
     * @param 版本
     * @return
     */
    @Autowired
    TplFormDao formDao;
    private TplForm getTpl(String 路径ID,String 版本){

        QueryWrapper<TplForm> query=new QueryWrapper<>();
        //query.eq("路径ID",路径ID);
        query.apply("CHARINDEX(',"+路径ID+",',','+路径ID+',')>0");

        List<TplForm> tplForms = formDao.selectList(query);
        if(tplForms.size()==0) {
            TplForm tplForm = new TplForm();
            tplForm.setRsize(3);
            return tplForm;
        };

        //匹配版本号，如果没找到，按 内科、操作、手术的顺序获取
        List<TplForm> tmps = tplForms.stream()
                .filter(it -> it.get版本().equals(版本))
                .sorted((a,b)->a.get版本().compareTo(b.get版本()))
                .collect(Collectors.toList());



        if(tmps.size()==0){
            return tplForms.get(0);
        }else {
            return tmps.get(0);
        }



    }

    Map<String, Object> generParams(PatientInfo info,TplForm tpl){

        Map<String, Object> map=new HashMap<>();
        //分组信息
        JSONObject grp=new JSONObject();
        grp.put("disname",info.getDisname());
        grp.put("discode",info.getDiscode());
        map.put("grp",grp);
        map.put("title",info.getDisname());

        map.put("pathway",tpl);
        //病人基本信息

        map.put("user",info);

        if(!StringUtils.isEmpty(info.getDrgcode())){
            JSONObject stdcost = stdcost(info.getDrgcode());
            map.put("std",stdcost);
        }
        //MCC LS
        JSONObject mccOrCC = MCCOrCC(info.getId());
        map.put("mccOrcc",mccOrCC);
        //手术信息
        //1.手术日期
        info.setSl(false);
        if(!StringUtils.isEmpty(info.getOptcode())&&!StringUtils.isEmpty(info.getDrgcode())){
            String pattern=".[A-J].*";
            if(Pattern.compile(pattern).matcher(info.getDrgcode()).matches()){
                Date oPtDate = patientDao.getOPtDate(info.getId(), info.getOptcode());
            info.setOptDate(oPtDate);
            info.setSl(true);
            grp.put("issl",true);
            grp.put("optname2",info.getOptname());
            grp.put("optname",info.getOptcode());
        }
        }
        //费用信息提取项目、药品等信息
        JSONArray 费用信息 = 费用信息(info, tpl);
        if(费用信息!=null){
            map.put("ps",费用信息);
        }

        return  map;
    }

    public static String fmt(Date d){

        SimpleDateFormat fm=new SimpleDateFormat("yyyy-MM-dd");

        return fm.format(d);
    }

    public JSONObject stdcost(String code){
        List<Map<String, Object>> 病组标植值 = pathTplDao.病组标植值(code);


        JSONObject o=new JSONObject();

        if(病组标植值.size()>0){
            Map<String, Object> map = 病组标植值.get(0);
            o.put("cost",map.get("平均费用"));
            o.put("bed",map.get("平均床日"));
            o.put("expended",map.get("平均药品费"));
            o.put("examfee",map.get("平均检查费"));
            o.put("surveyfee",map.get("平均检验费"));
            o.put("matfee",map.get("平均耗材费"));
            o.put("optfee",map.get("平均手术费"));
        }

        return o;
    }

    @Autowired
    VDCP费用记录Dao vdcp费用记录Dao;
    public JSONArray 费用信息(PatientInfo info,TplForm tpl){
        QueryWrapper<VDCP费用记录> q=new QueryWrapper<>();
        q.eq("病人标识",info.getId());
        List<VDCP费用记录> vdcp费用记录s = vdcp费用记录Dao.selectList(q);

        //获取全部获取编码，然后获取每个医保编码的名称信息
        List<String> 医保项目编码s = vdcp费用记录s.stream()
                .filter(it->!StringUtils.isEmpty(it.get医保项目编码()))
                .map(it -> it.get医保项目编码())
                .distinct().collect(Collectors.toList());

        List<W路径项目信息> 必须项目Ls = vdcp费用记录Dao.selectByDis2Must(info.getDiscode());

        //医保编码对应的项目
        List<W路径项目信息> w路径项目信息s = vdcp费用记录Dao.w路径项目信息(医保项目编码s);
        //方便查找转换为MAP
        Map<String,W路径项目信息> w路径项目信息Map=new HashMap<>();
        for (W路径项目信息 w路径项目信息 : w路径项目信息s) {
            w路径项目信息Map.put(w路径项目信息.get项目编码(),w路径项目信息);
        }

        Map<Integer,Set<String>> 按天数组织项目=new HashMap<>();
        //特殊项目：做了的就显示出来
        List<String> specialprojects = vdcp费用记录Dao.通过说明获取项目编码(Arrays.asList("血常规", "尿液分析", "粪便常规", "肝功", "葡萄糖测定", "血脂", "电解质", "肾功", "常规心电图", "X线摄影", "计算机X线摄影（ComputedRadiography，CR）"));

        Map<Integer,Double> 费用Map=new HashMap<>();

        for (VDCP费用记录 vdcp费用记录 : vdcp费用记录s) {

            boolean 需要的项目=(
                    //不是基础项目
                    (!vdcp费用记录.get是否基础项目()&&
                            (!StringUtils.isEmpty(vdcp费用记录.get适用疾病())&&vdcp费用记录.get适用疾病().contains(info.getDisname())

                            )&&!vdcp费用记录.get项目名称().contains("加收"))
                    ||必须项目Ls.stream().filter(it->it.get项目编码().equals(vdcp费用记录.get医保项目编码())).count()>0
                    ||specialprojects.contains(vdcp费用记录.get医保项目编码())
                    );

            int day=daysBetween(info.getItime(),vdcp费用记录.get发生时间());
            if(需要的项目){


                if(!按天数组织项目.containsKey(day)){
                    按天数组织项目.put(day,new HashSet<>());
                }

                Set<String> 项目Set=按天数组织项目.get(day);
                项目Set.add(vdcp费用记录.get医保项目编码());
            }

            Double amount = 费用Map.getOrDefault(day, 0D);
            费用Map.put(day,amount+vdcp费用记录.get金额());

        }




        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        class GrpInfo implements Serializable{
            private String grp;
            private List<W路径项目信息> ls;
        }

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        class RowInfo implements Serializable{

            private int day;

            private String amount;

            private String desc;

            private List<GrpInfo> grps;

            //诊疗描述
            private List<String> zl;
            //护理描述
            private List<String> fl;

        }


        List<RowInfo> rows=new ArrayList<>();

        //按项目编码组织项目信息 大类按以下顺序排序
        Map<String,Integer> 分类序列=new HashMap<String,Integer>(){
            {
                put("项目名称",1);
                put("建议用药",2);
                put("药品分类",3);
            }
        };

        /**
         *
         * 血常规、尿常规、大便常规、肝功、肾功、血脂、血糖、常规心电图、胸片 排序
         */
        Map<String, Integer> orderNumMap=new HashMap<String, Integer>(){
            {
                put("血常规", 1);
                put("血液分析", 2);
                put("尿常规", 3);
                put("尿液分析", 4);
                put("大便常规", 5);
                put("粪便常规", 6);
                put("肝功", 7);
                put("肾功", 8);
                put("血脂", 9);
                put("血糖", 10);
                put("常规心电图", 11);
                put("CT平扫", 12);
                put("胸片", 13);
                //这三个的顺序，最好是血常规、尿常规、粪便常规
            }
        };

        int 住院天数=daysBetween(info.getItime(),info.getOtime())+1;
        int 手术天数=1;
        if(info.getSl()){
            手术天数=daysBetween(info.getItime(),info.getOptDate())+1;
        }
        Map<Integer, Tuple2<List<String>, List<String>>> 诊疗工作Map = 生成诊疗工作And护理工作(住院天数, info.getSl(), 手术天数, tpl);


        for (Map.Entry<Integer, Set<String>> entry : 按天数组织项目.entrySet()) {

            List<W路径项目信息> ls=w路径项目信息s.stream().filter(it->entry.getValue().contains(it.get项目编码())).distinct().collect(Collectors.toList());


            //按分类键分组
            Map<String, List<W路径项目信息>> grp = ls.stream().collect(Collectors.groupingBy(W路径项目信息::get分类));


            //药品分类补齐
            String k="建议用药";
            if(grp.containsKey(k)){
                List<W路径项目信息> 药品分类 = grp.get(k).stream().map(it -> new W路径项目信息(it.get说明(), "药品分类")).distinct().collect(Collectors.toList());
                grp.put("药品分类",药品分类);
            }

            for (Map.Entry<String, List<W路径项目信息>> w : grp.entrySet()) {
                w.getValue().sort((a,b)->{

                    Integer a1=100;
                    Integer b1=100;

                    if(orderNumMap.containsKey(a.get名称())){
                        a1=orderNumMap.get(a.get名称());
                    }

                    if(orderNumMap.containsKey(b.get名称())){
                        b1=orderNumMap.get(b.get名称());
                    }

                    return a1-b1;

                });
            }

            List<GrpInfo> grpInfoes = grp.entrySet().stream().map(it -> new GrpInfo(it.getKey(), it.getValue())).collect(Collectors.toList());

            //大类排序
            grpInfoes.sort((a,b)->{
                if(分类序列.containsKey(a.grp)&&分类序列.containsKey(b.grp)){
                    int a1=分类序列.get(a.grp);
                    int b1=分类序列.get(b.grp);

                    return a1-b1;
                }else{
                    return a.grp.compareTo(b.grp);
                }
            });
            double amount=费用Map.get(entry.getKey());


            RowInfo rowInfo=new RowInfo(entry.getKey(),String.format("%.2f",amount),null,grpInfoes,null,null);


            rows.add(rowInfo);
        }

        //补齐没有天数的
        for (int i = 0; i < 住院天数; i++) {


            int finalI = i;
            Optional<RowInfo> optRowInfo = rows.stream().filter(it -> it.getDay() == finalI).findFirst();

            RowInfo rowInfo=new RowInfo();
            rowInfo.setDay(i);
            rowInfo.setAmount("0.00");
            if(费用Map.containsKey(i)){
                double amount=费用Map.get(i);
                rowInfo.setAmount(String.format("%.2f",amount));
            }

            List<W路径项目信息> projects=new ArrayList<W路径项目信息>(){
                {
                    add(new W路径项目信息(){
                        {
                            set名称("基础项目");
                        }
                    });
                }
            };
            rowInfo.setGrps(new ArrayList<GrpInfo>(){
                {
                    add(new GrpInfo("",projects));
                }
            });
            if(optRowInfo.isPresent()){
                rowInfo=optRowInfo.get();
            }else {
                rows.add(rowInfo);
            }

            List<String> zl=null,fl=null;
            if(诊疗工作Map.containsKey(i+1)){
                zl=诊疗工作Map.get(i+1).getFirst();
                fl=诊疗工作Map.get(i+1).getSecond();
            }
            if(info.getSl()){
                if(rowInfo.getDay()+1==手术天数){
                    rowInfo.setDesc("手术日");
                }
            }
            rowInfo.setFl(fl);
            rowInfo.setZl(zl);

            if(rowInfo.getDay()==0&&StringUtils.isEmpty(rowInfo.getDesc())){
                rowInfo.setDesc("入院日");
            }
            if(rowInfo.getDay()+1==住院天数&&StringUtils.isEmpty(rowInfo.getDesc())){
                rowInfo.setDesc("出院日");
            }
        }
        rows.sort((a,b)->a.getDay()-b.getDay());

        //转换成word能显示的格式

        JSONArray ps=new JSONArray();
        if(rows.size()>0){
            int size=tpl.getRsize();
            JSONObject o=new JSONObject();
            for (RowInfo row : rows) {

                int f=(row.getDay()+1)%size;
                o.put("f"+f,row);

                if(f==0){
                    ps.add(o);
                    o=new JSONObject();
                }
            }
            if(o.containsKey("f1")){
                ps.add(o);
            }
        }

        return ps.size()>0?ps:null;


    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class Tuple2<T1,T2>{

        private T1 first;
        private T2 second;
    }
    /**
     * 生成诊疗工作和护理工作
     * @param days 住院天数
     * @param opt 是否做过手术
     * @param optDay 手术日是哪天
     * ┏━━━┳━━━┳━━━━━┳━━━━━┳━━━━━┳━━━━━━┳━━━━━━┳━━━━━┳━━━━━┓
     * ┃内科    ┃入院日┃住院期间1 ┃住院期间2 ┃住院期间3 ┃住院期间4     ┃ 住院期间5    ┃  出院前      ┃ 出院日       ┃
     * ┣━━━╋━━━╋━━━━━╋━━━━━╋━━━━━╋━━━━━━╋━━━━━━╋━━━━━╋━━━━━┫
     * ┃优先级┃    1     ┃         4        ┃          5       ┃          6       ┃           7          ┃       8              ┃       3          ┃   2              ┃
     * ┣━━━╋━━━╋━━━━━╋━━━━━╋━━━━━╋━━━━━━╋━━━━━━╋━━━━━╋━━━━━┫
     * ┃外科    ┃处院日┃  手术前1   ┃ 手术前2    ┃  手术日      ┃       术后1      ┃    术后2         ┃    出院前    ┃出院日        ┃
     * ┣━━━╋━━━╋━━━━━╋━━━━━╋━━━━━╋━━━━━━╋━━━━━━╋━━━━━╋━━━━━┫
     * ┃优先级┃   3	     ┃          4       ┃       8          ┃        1         ┃          5           ┃         7            ┃       6          ┃   2              ┃
     * ┣━━━┻━━━┻━━━━━┻━━━━━┻━━━━━┻━━━━━━┻━━━━━━┻━━━━━┻━━━━━┫
     * ┃                                                    如果是入院当前手术， 则没有手术日前的内容                                                                       ┃
     * ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
     * @return
     */
    private Map<Integer, Tuple2<List<String>, List<String>>> 生成诊疗工作And护理工作(int days,boolean opt,int optDay,TplForm way){


        Map<Integer, Tuple2<List<String>, List<String>>> rsMap=new HashMap<Integer, Tuple2<List<String>,List<String>>>();


        //设置优先级列表
        Map<Integer, Tuple2<String, String>> colMap=new HashMap<Integer, Tuple2<String, String>>(){
            {
                put(1, new Tuple2<String, String>(way.getInadmision10(), way.getInadmision11()));
                put(4, new Tuple2<String, String>(way.getInhospital10(), way.getInhospital11()));
                put(5, new Tuple2<String, String>(way.getInhospital20(), way.getInhospital21()));
                put(6, new Tuple2<String, String>(way.getInhospital30(), way.getInhospital31()));
                put(7, new Tuple2<String, String>(way.getInhospital40(), way.getInhospital41()));
                put(8, new Tuple2<String, String>(way.getInhospital50(), way.getInhospital51()));
                put(3, new Tuple2<String, String>(way.getBeforeadmision10(), way.getBeforeadmision11()));
                put(2, new Tuple2<String, String>(way.getOutadmision10(), way.getOutadmision11()));
            }
        };

        if(opt){

            colMap=new HashMap<Integer, Tuple2<String, String>>(){
                {
                    //入院日诊疗
                    put(-1, new Tuple2<String, String>(way.getInadmision10(), way.getInadmision11()));
                    //住院期间1诊疗（手术前1）
                    put(-2, new Tuple2<String, String>(way.getInhospital10(), way.getInhospital11()));
                    //住院期间2护理（手术前2）
                    put(-3, new Tuple2<String, String>(way.getInhospital20(), way.getInhospital21()));

                    put(0, new Tuple2<String, String>(way.getInhospital30(), way.getInhospital31()));
                    put(2, new Tuple2<String, String>(way.getInhospital40(), way.getInhospital41()));
                    put(4, new Tuple2<String, String>(way.getInhospital50(), way.getInhospital51()));
                    put(3, new Tuple2<String, String>(way.getBeforeadmision10(), way.getBeforeadmision11()));
                    put(1, new Tuple2<String, String>(way.getOutadmision10(), way.getOutadmision11()));
                }
            };
        }

        String reg="\\r*\\n";
        if(!opt){
            //如果是当天入院当天出院 生成入院与出院诊疗工作和护理工作
            List<Tuple2<List<String>, List<String>>> rs=new LinkedList<Tuple2<List<String>,List<String>>>();
            for(int i=1;i<=days;i++){
                Integer k=i>8?8:i;
                String zl=colMap.get(k).getFirst();
                String fl=colMap.get(k).getSecond();

                List<String> zlLs=new ArrayList<String>();
                List<String> flLs=new ArrayList<String>();
                if(!StringUtils.isEmpty(zl)){
                    zlLs=Arrays.asList(zl.split(reg));
                }
                if(!StringUtils.isEmpty(fl)){
                    flLs=Arrays.asList(fl.split(reg));
                }
                if(i<=2){
                    rs.add(new Tuple2<List<String>, List<String>>(zlLs, flLs));
                }else if(i==3) {
                    rs.add(1,new Tuple2<List<String>, List<String>>(zlLs, flLs));
                }else {
                    rs.add(i-3,new Tuple2<List<String>, List<String>>(zlLs, flLs));
                }

            }
            //System.out.println(JSON.toJSON(rs));
            for (int i=0;i<rs.size();i++) {
                rsMap.put(i+1, rs.get(i));
            }

        }else {

            int ii=1;
            //手术前
            int mp=optDay*-1+1;

//			//入院日诊疗
//			put(-1, new Tuple2<String, String>(way.getInadmision10(), way.getInadmision11()));
//			//住院期间1诊疗（手术前1）
//			put(-2, new Tuple2<String, String>(way.getInhospital10(), way.getInhospital11()));
//			//住院期间2护理（手术前2）
//			put(-3, new Tuple2<String, String>(way.getInhospital20(), way.getInhospital21()));

            for(int i=mp;i<=0;i++){


                int k=i;
                //入院日诊断
                if(i==mp){
                    k=-1;
                } else if(i==-1){//手术前一天
                    k=-2;
                }else if(i==-2){//手术第二天
                    k=-3;
                }
                else{
                    k=k<-3?-3:k;
                }


                String zl=colMap.get(k).getFirst();
                String fl=colMap.get(k).getSecond();

                List<String> zlLs=new ArrayList<String>();
                List<String> flLs=new ArrayList<String>();
                if(!StringUtils.isEmpty(zl)){
                    zlLs=Arrays.asList(zl.split(reg));
                }
                if(!StringUtils.isEmpty(fl)){
                    flLs=Arrays.asList(fl.split(reg));
                }
                rsMap.put(ii++, new Tuple2<List<String>, List<String>>(zlLs,flLs));

            }

            int sh=days-optDay;
            //System.out.println("sh="+sh);
            //1、术后一天：出院
            //2、术后两天:术后1天、出院
            //3、术后三天:术后1天、出院前、出院
            //4、术后四天：术后1天、术后2天、出院前、出院
            //5、术后五天：术后1天、术后2天、术后2天、出院前、出院
            List<Integer> ids=new ArrayList<Integer>();
            switch (sh) {
                case 0:break;
                case 1:
                    ids.add(1);//术后一天：出院
                    break;
                case 2:
                    ids.addAll(Arrays.asList(2,1));//术后两天:术后1天、出院
                    break;
                case 3:
                    ids.addAll(Arrays.asList(2,3,1));//术后1天、出院前、出院
                    break;
                default:
                    //4、术后四天：术后1天、术后2天、出院前、出院
                    //5、术后五天：术后1天、术后2天、术后2天、出院前、出院
                    //6、填充术后2
                    ids.add(2);
                    for(int i=1;i<sh-2;i++) ids.add(4);
                    ids.addAll(Arrays.asList(3,1));
                    break;
            }
            for (Integer k : ids) {
                //System.out.println(k);
                String zl=colMap.get(k).getFirst();
                String fl=colMap.get(k).getSecond();

                List<String> zlLs=new ArrayList<String>();
                List<String> flLs=new ArrayList<String>();
                if(!StringUtils.isEmpty(zl)){
                    zlLs=Arrays.asList(zl.split(reg));
                }
                if(!StringUtils.isEmpty(fl)){
                    flLs=Arrays.asList(fl.split(reg));
                }
                rsMap.put(ii++, new Tuple2<List<String>, List<String>>(zlLs,flLs));
            }

        }
        return rsMap;

    }




    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     */
    public static int daysBetween(Date smdate,Date bdate)
    {
       try {
           SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
           smdate=sdf.parse(sdf.format(smdate));
           bdate=sdf.parse(sdf.format(bdate));
           Calendar cal = Calendar.getInstance();
           cal.setTime(smdate);
           long time1 = cal.getTimeInMillis();
           cal.setTime(bdate);
           long time2 = cal.getTimeInMillis();
           long between_days=(time2-time1)/(1000*3600*24);

           return Integer.parseInt(String.valueOf(between_days));
       }catch (Exception ex){
           return  0;
       }
    }


    public static TextRenderData compute(Object val, Object stdVal) {
        String str=val+"/"+stdVal;
        double f=Double.parseDouble(val.toString())/Double.parseDouble(stdVal.toString());
        //默认黑色
        String color="000000";
        //大于20% 红色
        if(f>1.2){
            color="FF0000";
        }
        //蓝色
        if(f<=0.8) color="0000C6";

        return Texts.of(str).color(color).create();
    }



    private JSONObject MCCOrCC(String id){
        List<Map<String, Object>> 诊断信息 = patientDao.诊断信息(id);
        JSONArray ls=new JSONArray();
        诊断信息.stream().filter(it->{
            String zdlx = it.get("ZDLX").toString();
            if(zdlx.equals("出院诊断")){
                if(it.containsKey("并发症状态")){
                    String 并发症状态=it.get("并发症状态").toString();
                    //MCC或CC
                    return 并发症状态.equals("1")||并发症状态.equals("2");
                }

            }

            return false;
        }).forEach(it->{
            JSONObject o=new JSONObject();

            o.put("code",it.getOrDefault("JBBM",""));
            o.put("name",it.getOrDefault("ZDMS",""));

            ls.add(o);
        });

        JSONObject o=new JSONObject();
        o.put("have",ls.size()>0);
        o.put("ls",ls);

        return o;
    }


}
